<template>
  <div class="base64atob">
    <label class="title" for="textData">base64编码</label>
    <textarea id="textData" cols="30" rows="10" v-model="textData"></textarea>
    <div class="yh-results">编码结果：<p class="yh-results-text">{{toBase64Data}}</p></div>
    <label class="title" for="base64Data">base64解码</label>
    <textarea id="base64Data" cols="30" rows="10" v-model="base64Data"></textarea>
    <div class="yh-results">解码结果：<p class="yh-results-text">{{toTextData}}</p></div>
    <pre v-highlightjs class="code-pre">
      <code class="javascript">
        /**
         * window API中的 atob 可以将base64解码
         */
        try {
          this.toTextData = window.atob(this.base64Data)
        } catch (e) {
          this.toTextData = `输入错误`
        }
        /**
         * window API中的 btoa 可以进行base64编码
         * (中文需先使用encodeURIComponent)
         */
        try {
          this.toBase64Data = window.btoa(this.textData)
        } catch (e) {
          this.toBase64Data = `输入错误`
        }
      </code>
    </pre>
  </div>
</template>

<script>
  export default {
    name: "base64atob",
    data() {
      return {
        base64Data: '',
        toTextData: '',
        textData: '',
        toBase64Data: ''
      }
    },
    watch: {
      base64Data(newVal, oldVal) {
        try {
          this.toTextData = window.atob(this.base64Data)
        } catch (e) {
          this.toTextData = `输入错误`
        }
      },
      textData(newVal, oldVal) {
        try {
          this.toBase64Data = window.btoa(this.textData)
        } catch (e) {
          this.toBase64Data = `输入错误`
        }

      }
    }
  }
</script>

<style scoped>
  .base64atob {
    width: 1000px;
    display: flex;
    justify-content: flex-start;
    align-items: flex-start;
    flex-flow: column;
  }

  .title {
    font-weight: 700;
    font-size: 16px;
  }

  #textData, #base64Data {
    width: 600px;
    height: 100px;
    resize: none;
    padding: 6px;
  }

  .yh-results {
    font-weight: 700;
    margin: 10px 0;
    margin-bottom: 30px;
  }

  .yh-results-text {
    word-break: break-all;
    color: dodgerblue;
    display: inline-block;
  }
</style>
